import Vue from "vue";
import VueRouter from "vue-router";
import store from "@/store/index.js";
import Main from "@/views/Main";
import Home from "@/views/Home";
import Community from "@/views/Community";
import Message from "@/views/Message";
import User from "@/views/User";
import TeacherDetail from "@/views/TeacherDetail";
import ArticleDetail from "@/views/ArticleDetail";
import UserHome from "@/views/UserHome";
import UserProfile from "@/views/UserProfile";
import Login from "@/views/Login";
import ArticlePub from "@/views/ArticlePub";
import Users from "@/views/Users";
import Chat from "@/components/Chat/Chat";
import Notifications from "@/views/Notifications";
import Search from "@/views/SearchPage";
import SearchResult from '@/views/SearchResult.vue';
Vue.use(VueRouter);

const routes = [{
        path: "/login",
        component: Login,
    },
    {
        path: "/",
        component: Main,
        name: "main",
        redirect: "/home",
        children: [{
                path: "home",
                name: "home",
                component: Home,
            },
            {
                path: "community",
                name: "community",
                component: Community,
            },
            {
                path: "message",
                name: "message",
                component: Message,
            },
            {
                path: "/user",
                name: "user",
                redirect: "/user/home",
                component: User,
                children: [{
                        path: "home",
                        component: UserHome,
                    },
                    {
                        path: "profile",
                        component: UserProfile,
                    },
                ],
            },
        ],
    },
    {
        path: "/teachers/:id",
        component: TeacherDetail,
        props: true,
    },
    {
        path: "/community/:id",
        component: ArticleDetail,
        props: true,
    },
    {
        path: "/article/pub",
        component: ArticlePub,
    },
    {
        path: "/users/:id",
        component: Users,
        props: true,
    },
    {
        path: "/chat/:id",
        component: Chat,
        props: true,
    },
    {
        path: "/notifications",
        component: Notifications
    },
    {
        path: "/search",
        component: Search
    },
    {
        path: '/search/:kw',
        component: SearchResult,
        name: 'search-result',
        props: true
    }
];

const router = new VueRouter({
    routes,
});

// 所有有权限页面的路径，都在这个数组之中
const pagePathArr = ["/user/home", "/user/edit", "/user/profile", "/comments"];

// 为路由的实例对象挂载全局前置守卫
router.beforeEach((to, from, next) => {
    // 访问的是有权限的页面，需要判断用户是否登录
    if (pagePathArr.indexOf(to.path) !== -1) {
        // 1. 从 store 中获取 token 的值
        //    注意：store.state.tokenInfo 要么是 {} 空对象，要么是包含 {token, refresh_token} 的对象
        const tokenStr = store.state.user.tokenInfo.token;
        if (tokenStr) {
            // 1.1 token 有值，已登录过（操作：直接放行）
            next();
        } else {
            // 1.2 token 不存在，没有登录（操作：强制跳转到登录页）
            next(`/login?pre=${to.fullPath}`);
        }
    } else {
        // 访问的是没有权限的页面
        next();
    }
});

// 连接websocket
router.beforeEach((to, from, next) => {
    const token = store.state.user.tokenInfo.token
    if (!store.state.chat.socket) {
        if (token) {
            store.commit("chat/initWebSocket", token);
        }
    }
    next()
})

// 1. 将 VueRouter 本身提供的 $router.push 方法转存到常量中
const originalPush = VueRouter.prototype.push;
// 2. 自定义 $router.push 方法，在内部调用原生的 originalPush 方法进行路由跳转；并通过 .catch 捕获错误
VueRouter.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject)
        return originalPush.call(this, location, onResolve, onReject);
    // 通过 .catch 捕获错误
    return originalPush.call(this, location).catch((err) => err);
};

export default router;